<template>
	<div class="app-mob-color-picker">
		<van-field v-model="curValue" :disabled="disabled" :style="{ color: curColor }" @focus="handleFocus" @blur="handleBlur" @input="handleChange">
			<template #extra>
				<AppMobVantColorPicker v-bind="$attrs" :disabled="disabled" :color="curColor" @colorChange="handleColorChange" />
			</template>
		</van-field>
	</div>
</template>
<script setup lang="ts">
import { defineComponent, ref, Ref, onMounted, reactive, defineProps } from 'vue';
import { AppMobVantColorPicker } from './components/vant-color-picker';
import { colorPickerProps } from './color-picker';
import { useEditorTypeParams } from '@/hooks/use-editor';
import { IEvent } from '@/core';

interface EditorEmit {
	(name: 'editor-event', value: IEvent<string>): void;
}
const props = defineProps(colorPickerProps);
const emit = defineEmits<EditorEmit>();
// 类型校验
const { validateConfig } = useEditorTypeParams();
validateConfig();
const curValue = ref('');
const tempColor = ref('');

watch(
	() => props.value,
	(newVal: any, oldVal: any) => {
		curValue.value = newVal;
	},
	{
		immediate: true,
	}
);
const handleChange = ($event: any) => {
	const { target } = $event;
	if (!target) {
		return;
	}
	emit('editor-event', {
		name: props.name,
		action: 'valueChange',
		data: target.value,
	});
};

const curColor = computed(() => {
	if (props.color && props.data[props.color]) {
		return props.data[props.color];
	} else if (tempColor.value) {
		return tempColor.value;
	}
});

const handleFocus = ($event: any) => {
	const { target } = $event;
	if (!target) {
		return;
	}
	emit('editor-event', {
		name: props.color,
		action: 'editorFocus',
		data: target.value,
	});
};
const handleBlur = ($event: any) => {
	const { target } = $event;
	if (!target) {
		return;
	}
	emit('editor-event', {
		name: props.color,
		action: 'editorBlur',
		data: target.value,
	});
};

const handleColorChange = (color: string) => {
	tempColor.value = color;
	if (props.color) {
		emit('editor-event', {
			name: props.color,
			action: 'valueChange',
			data: color,
		});
	}
}
</script>